﻿﻿﻿function WebTcpSocket(){
	var socket = new Object;
	socket.ip = '';
	socket.userId='';
	socket.WS = null;
	socket.sinterval = null;
	socket.loginstatus = 0;
	socket.lastLoginTime = 0;
	socket.lastHeartTime = 0;
	socket.randPort = GetRandomNum_E(100000,999999);
	socket.MessageBack=function(msg){
		var ss = msg;
		console.log(JSON.stringify(ss));
	};
	socket.initSocket = function(aIp,aUserId,callMsg){
		socket.ip = aIp;
		socket.MessageBack = callMsg;
		socket.userId=aUserId;
		//socket.sinterval = setInterval(function(){socket.socketHeart()},200);				
		
	};
	socket.init = function(){
		socket.WS = new WebSocket(socket.ip);
		socket.WS.onmessage=function(obj){
			console.log(getCurrentTime()+'-->socket msg:'+obj.data);
			var data = $.parseJSON( obj.data );
			if(data!=null){
				if(data.cmd=='msg'){
					if(data&&socket.MessageBack){
						socket.MessageBack(data.content);
					}
				}else if(data.cmd=='heart'){
					socket.lastHeartTime = new Date().getTime();
				}else if(data.cmd=='login'){
					socket.loginstatus = 2;
				}
			}	
		};
		socket.WS.onopen = function(){
			socket.loginstatus = 1;			
		}
		socket.WS.onclose=function(e){
			socket.loginstatus = 0;
			console.log('断开原因：'+e.code+'--->'+e.reason);	
			console.log(e);
			socket.WS=null;
		};
		socket.WS.onerror=function(error){
			socket.loginstatus = 0;
			console.log(error);
			socket.WS=null;			
		}
	};
	socket.socketHeart = function(){
		let d = new Date().getTime();
		if(socket.loginstatus == 0&&socket.WS==null){
			socket.init();
		}
		if(socket.loginstatus == 1 && d-socket.lastLoginTime>1000*30 && socket.WS.readyState==WebSocket.OPEN){
			socket.lastLoginTime = d;
			socket.WS.send('{"cmd":"Login","rand":"'+socket.randPort+'","userId":"'+socket.userId+'","loginType":0}');
		}
		if(socket.loginstatus == 2 && d-socket.lastHeartTime>1000*14 && socket.WS.readyState==WebSocket.OPEN){
			socket.lastHeartTime = d;
			socket.WS.send('{"cmd":"Heartbeat"}');
		}
	};
	setInterval (function(){socket.socketHeart();},1000);
	return socket;
}

function GetRandomNum_E(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return(Min + Math.round(Rand * Range));
}

function getCurrentTime(){
	var date = new Date();
	var yyyy = date.getFullYear();
	var month = repair(date.getMonth()+1);
	return yyyy+"-"+month+"-"+repair(date.getDate())+ " "+repair(date.getHours())
		+":"+repair(date.getMinutes())+":"+repair(date.getSeconds());
}
function repair(i){
	if(i<10){
		return "0"+i;
	}else{
		return i;
	}
}